<?php

//power by wshoto.com
if (!defined('IN_IA')) {
    die('Access Denied');
}
global $_W, $_GPC;

function sortByCreateTime($a, $b)
{
    if ($a['createtime'] == $b['createtime']) {
        return 0;
    } else {
        return $a['createtime'] < $b['createtime'] ? 1 : -1;
    }
}

$openid = m('user')->getOpenid();
$set = m('common')->getSysset(array('shop', 'trade'));
$member = m('member')->getInfo($openid);

$commission = p('commission');

$orderMember = $commission->getInfo($openid, array('ordercount0'));
$agentLevel = $commission->getLevel($openid);
$set = $commission->getSet();
$level = intval($set['level']);

$commissioncount = 0;

$status = trim($_GPC['status']);
$condition = ' and o.status>=0';
if ($status != '') {
    $condition = ' and o.status=' . intval($status);
}
if($status == 6){
    $condition = ' and o.status>0';
}

$split = false;     // 佣金切割。
if(!empty($member['upleveltime'])){
    $split = true;
}

$partOrders = array();
$level1 = $orderMember['level1'];
$level2 = $orderMember['level2'];
$level3 = $orderMember['level3'];

$commission_ok = 0;

$ordercount = $orderMember['ordercount0'];
if ($level >= 1) {
    $level1_memberids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where uniacid=:uniacid and agentid=:agentid', array(':uniacid' => $_W['uniacid'], ':agentid' => $orderMember['id']), 'id');
    $sql = 'select commission1,o.id,o.createtime,o.finishtime,o.price from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . " where o.uniacid=:uniacid and o.agentid=:agentid {$condition} and og.status1>=0";

    $level1_orders = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid'], ':agentid' => $orderMember['id']));
    foreach ($level1_orders as $o) {
        if (empty($o['id'])) {
            continue;
        }
        $orderCommission = iunserializer($o['commission1']);

        if($split && $member['upleveltime'] > $o['finishtime']){
            $commission_ok += isset( $orderCommission['level' . $member['oldlevel']] ) ? $orderCommission['level' . $member['oldlevel']] : $orderCommission['default'];
        }else{
            $commission_ok += isset( $orderCommission['level' . $member['agentlevel']] ) ? $orderCommission['level' . $member['agentlevel']] : $orderCommission['default'];
        }

        //$commission_ok = isset($orderCommission['level' . $agentLevel['id']]) ? $orderCommission['level' . $agentLevel['id']] : $orderCommission['default'];
        $hasorder = false;
        foreach ($partOrders as &$or) {
            if ($or['id'] == $o['id'] && $or['level'] == 1) {
                $or['commission'] += $commission_ok;
                $hasorder = true;
                break;
            }
        }
        unset($or);
        if (!$hasorder) {
            $partOrders[] = array('id' => $o['id'], 'commission' => $commission_ok, 'createtime' => $o['createtime'], 'level' => 1);
        }
        $commissioncount += $commission_ok;
    }
}
if ($level >= 2) {
    if ($level1 > 0) {
        $level2_orders = pdo_fetchall('select commission2 ,o.id,o.createtime,o.finishtime,o.price   from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . " where o.uniacid=:uniacid and o.agentid in( " . implode(',', array_keys($orderMember['level1_agentids'])) . ")  {$condition}  and og.status2>=0 ", array(':uniacid' => $_W['uniacid']));
        foreach ($level2_orders as $o) {
            if (empty($o['id'])) {
                continue;
            }
            $orderCommission = iunserializer($o['commission2']);

            if($split && $member['upleveltime'] > $o['finishtime']){
                $commission_ok += isset( $orderCommission['level' . $member['oldlevel']] ) ? $orderCommission['level' . $member['oldlevel']] : $orderCommission['default'];
            }else{
                $commission_ok += isset( $orderCommission['level' . $member['agentlevel']] ) ? $orderCommission['level' . $member['agentlevel']] : $orderCommission['default'];
            }

            //$commission_ok = isset($orderCommission['level' . $agentLevel['id']]) ? $orderCommission['level' . $agentLevel['id']] : $orderCommission['default'];
            $hasorder = false;
            foreach ($partOrders as &$or) {
                if ($or['id'] == $o['id'] && $or['level'] == 2) {
                    $or['commission'] += $commission_ok;
                    $hasorder = true;
                    break;
                }
            }
            unset($or);
            if (!$hasorder) {
                $partOrders[] = array('id' => $o['id'], 'commission' => $commission_ok, 'createtime' => $o['createtime'], 'level' => 2);
            }
            $commissioncount += $commission_ok;
        }
    }
}
if ($level >= 3) {
    if ($level2 > 0) {
        $level3_orders = pdo_fetchall('select commission3 ,o.id,o.createtime,o.finishtime,o.price  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . ' where o.uniacid=:uniacid and o.agentid in( ' . implode(',', array_keys($orderMember['level2_agentids'])) . ")  {$condition} and og.status3>=0", array(':uniacid' => $_W['uniacid']));
        foreach ($level3_orders as $o) {
            if (empty($o['id'])) {
                continue;
            }
            $orderCommission = iunserializer($o['commission3']);

            if($split && $member['upleveltime'] > $o['finishtime']){
                $commission_ok += isset( $orderCommission['level' . $member['oldlevel']] ) ? $orderCommission['level' . $member['oldlevel']] : $orderCommission['default'];
            }else{
                $commission_ok += isset( $orderCommission['level' . $member['agentlevel']] ) ? $orderCommission['level' . $member['agentlevel']] : $orderCommission['default'];
            }

            //$commission_ok = isset($orderCommission['level' . $agentLevel['id']]) ? $orderCommission['level' . $agentLevel['id']] : $orderCommission['default'];
            $hasorder = false;
            foreach ($partOrders as &$or) {
                if ($or['id'] == $o['id'] && $or['level'] == 3) {
                    $or['commission'] += $commission_ok;
                    $hasorder = true;
                    break;
                }
            }
            unset($or);
            if (!$hasorder) {
                $partOrders[] = array('id' => $o['id'], 'commission' => $commission_ok, 'createtime' => $o['createtime'], 'level' => 3);
            }
            $commissioncount += $commission_ok;
        }
    }
}

usort($partOrders, 'sortByCreateTime');
$commissioncount = number_format($commissioncount, 2);

if ($_W['isajax']) {

    $member = m('member')->getInfo($openid);

    $member['credit1'] = number_format($member['credit1'], 0);
    $member['credit2'] = number_format($member['credit2'], 2);
    $level = array('levelname' => empty($set['shop']['levelname']) ? '普通会员' : $set['shop']['levelname']);
    if (!empty($member['level'])) {
        $level = m('member')->getLevel($openid);
    }
    $orderparams = array(':uniacid' => $_W['uniacid'], ':openid' => $openid);
    $order = array('status0' => pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_order') . ' where openid=:openid and status=0  and uniacid=:uniacid limit 1', $orderparams), 'status1' => pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_order') . ' where openid=:openid and status=1 and refundid=0 and uniacid=:uniacid limit 1', $orderparams), 'status2' => pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_order') . ' where openid=:openid and status=2 and refundid=0 and uniacid=:uniacid limit 1', $orderparams), 'status4' => pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_order') . ' where openid=:openid and refundid<>0 and uniacid=:uniacid limit 1', $orderparams));
    if (mb_strlen($member['nickname'], 'utf-8') > 6) {
        $member['nickname'] = mb_substr($member['nickname'], 0, 6, 'utf-8');
    }
    $open_creditshop = false;
    $creditshop = p('creditshop');
    if ($creditshop) {
        $creditshop_set = $creditshop->getSet();
        if (!empty($creditshop_set['centeropen'])) {
            $open_creditshop = true;
        }
    }

    $unPayNum = 0;
    $hasPayNum = 0;
    $totalPrice = 0 ;
    $totalCommission = 0;
    $pindex = max(1, intval($_GPC['page']));
    $psize = 20;

    $orders1 = array_slice($partOrders, ($pindex - 1) * $psize, $psize);

    $orderids = array();
    foreach ($orders1 as $o) {

        $orderids[$o['id']] = $o;
    }
    $list = array();


    if (!empty($orderids)) {

        $sql = 'SELECT `id`, `ordersn`, `createtime`, `finishtime`, `status`, `price` FROM '.tablename('ewei_shop_order'). ' WHERE `uniacid` = :uniacid  AND `id` in ('. implode(',', array_keys($orderids)) .') ORDER BY `id` DESC' ;
        $list = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid']));

        foreach ($list as &$row){

            $row['commission'] = number_format($orderids[$row['id']]['commission'], 2);
            $row['createtime'] = date('Y-m-d H:i', $row['createtime']);
            if ($row['status'] == 0) {
                $row['status'] = '待付款';
                $unPayNum =  $unPayNum + 1;
                $totalPrice = $totalPrice + $row['price'];
                $totalCommission = $totalCommission + $row['commission'];
            } else {
                if ($row['status'] == 1) {
                    $row['status'] = '已付款';
                    $hasPayNum = $hasPayNum + 1;
                    $totalPrice = $totalPrice + $row['price'];
                    $totalCommission = $totalCommission + $row['commission'];
                } else {
                    if ($row['status'] == 2) {
                        $row['status'] = '待收货';
                        $hasPayNum = $hasPayNum + 1;
                        $totalPrice = $totalPrice + $row['price'];
                        $totalCommission = $totalCommission + $row['commission'];
                    } else {
                        if ($row['status'] == 3) {
                            $row['status'] = '已完成';
                            $hasPayNum = $hasPayNum + 1;
                            $totalPrice = $totalPrice + $row['price'];
                            $totalCommission = $totalCommission + $row['commission'];
                        }
                    }
                }
            }
            if ($orderids[$row['id']]['level'] == 1) {
                $row['level'] = '一';
            } else {
                if ($orderids[$row['id']]['level'] == 2) {
                    $row['level'] = '二';
                } else {
                    if ($orderids[$row['id']]['level'] == 3) {
                        $row['level'] = '三';
                    }
                }
            }
        }
        unset($row);
    }

    show_json(1, array('member' => $member,'totalPrice' => $totalPrice, 'totalCommission' => $totalCommission,'unPayNum' => $unPayNum,'hasPayNum'=>$hasPayNum, 'order' => $order, 'level' => $level, 'open_creditshop' => $open_creditshop, 'list' => $list, 'pagesize' => $psize,'debug'=>$partOrders));
}

include $this->template('member/order');